<template>
    <a-row class="templateManagePage">
        <a-col :span="18">
            <div>
                <div class="header">
                    <a-input v-model:value="name" placeholder="配置名称" />
                    <a-button type="primary" @click="handleSave"> 保存 </a-button>
                </div>
            </div>
            <a-transfer
                :data-source="dataSource"
                v-model:target-keys="targetKeys"
                :disabled="false"
                :show-search="false"
                :titles="[' 全部字段', ' 模板列表']"
                :show-select-all="false"
                :render="item => item.title"
                @change="onChange"
            >
                <template
                    #children="{
                        direction,
                        filteredItems,
                        selectedKeys,
                        disabled: listDisabled,
                        onItemSelectAll,
                        onItemSelect
                    }"
                >
                    <div v-if="direction === 'right'">
                        <a-table
                            :row-selection="
                                getRowSelection({
                                    disabled: listDisabled,
                                    selectedKeys,
                                    onItemSelectAll,
                                    onItemSelect
                                })
                            "
                            :columns="tableColumns"
                            :data-source="filteredItems"
                            size="small"
                            :style="{ pointerEvents: listDisabled ? 'none' : null }"
                            :custom-row="
                                ({ key, disabled: itemDisabled }) => ({
                                    on: {
                                        click: () => {
                                            if (itemDisabled || listDisabled) return
                                            onItemSelect(key, !selectedKeys.includes(key))
                                        }
                                    }
                                })
                            "
                        />
                    </div>
                </template>
            </a-transfer>
        </a-col>
        <a-col :span="6">
            <div class="template-list">
                <div class="title"> 模板列表 </div>
                <a-table
                    :columns="tableListColumns"
                    :data-source="exportTemplateList"
                    :row-key="record => record.name"
                    size="small"
                >
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'action'">
                            <a @click="handlerDeleteConfirm(record.id)">删除</a>
                        </template>
                    </template>
                </a-table>
            </div>
        </a-col>
    </a-row>
</template>

<script lang="ts">
    import { defineComponent, onMounted, watch, computed, ref } from 'vue'
    import { Modal, message as createMessage } from 'ant-design-vue'
    import { isNullOrUnDef, isEmptyArr } from '@/utils/is'

    export default defineComponent({
        name: 'TemplateManage',
        props: {
            //table列
            columList: {
                type: Array,
                default: () => {
                    return []
                }
            },
            //应用编码
            applicationId: {
                type: Number
            },
            //数据源id
            pageId: {
                type: Number
            },
            addExportTemplate: {
                type: Function
            },
            deleteExportTemplate: {
                type: Function
            },
            getExportTemplate: {
                type: Function
            }
        },
        setup(props) {
            const tableColumns = ref([
                {
                    dataIndex: 'title',
                    title: '字段名称'
                },
                {
                    dataIndex: 'key',
                    title: '字段Key'
                }
            ])
            const tableListColumns = ref([
                {
                    dataIndex: 'name',
                    title: '名称'
                },
                {
                    title: '操作',
                    fixed: 'right',
                    dataIndex: 'action',
                    width: 100,
                    scopedSlots: { customRender: 'action' }
                }
            ])
            const selectLeft = ref([])
            const targetKeys = ref([])
            const name = ref('')
            const exportTemplateList = ref([]) // 可用的导出模板数据列表
            const formId = computed(() => {
                return props.pageId
            })
            const noCloumn = ['sequenceNumber', 'operation']
            const dataSource = computed(() => {
                const data = []
                props.columList
                    ?.filter(item => !noCloumn.includes(item.dataIndex))
                    .forEach(item => {
                        data.push({
                            key: item.dataIndex,
                            title: item.title,
                            disabled: !(isNullOrUnDef(item.children) || isEmptyArr(item.children))
                        })
                        if (!isNullOrUnDef(item.children)) {
                            data.push(
                                ...item.children.map(info => ({
                                    key: info.dataIndex,
                                    title: info.title
                                }))
                            )
                        }
                    })
                return data
            })
            const getExportTemplateList = () => {
                const data = {
                    pageNo: 1, // 分页页码
                    pageSize: 100, // 分页条数
                    sort: {
                        // 支持多排序
                    },
                    filter: {
                        // 过滤条件
                        pageId: formId.value, // 当前表单id
                        deleted: false
                    }
                }
                props.getExportTemplate(data).then(res => {
                    exportTemplateList.value = res.data.content
                })
            }
            const onChange = nextTargetKeys => {
                targetKeys.value = nextTargetKeys
            }
            const handlerDeleteConfirm = id => {
                // TODO
                Modal.confirm({
                    content: '删除后无法恢复，是否继续删除该模板?',
                    onOk() {
                        deleteOne(id)
                    }
                })
            }
            const deleteOne = id => {
                props.deleteExportTemplate({ idList: [id] }).then(() => {
                    createMessage.success('删除成功')
                    getExportTemplateList()
                })
            }
            const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
                return {
                    getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
                    onSelectAll(selected, selectedRows) {
                        const treeSelectedKeys = selectedRows.filter(item => !item.disabled).map(({ key }) => key)
                        onItemSelectAll(treeSelectedKeys, selected)
                    },
                    onSelect({ key }, selected) {
                        onItemSelect(key, selected)
                    },
                    selectedRowKeys: selectedKeys
                }
            }
            const initData = () => {
                name.value = ''
                selectLeft.value = []
                targetKeys.value = []
            }
            const handleSave = () => {
                const templateNameList = exportTemplateList.value.map(item => item.name)
                if (templateNameList.includes(name.value)) {
                    createMessage.error('列明已存在')
                    return
                }
                const { status, message } = checkTableData()
                if (!status) {
                    createMessage.error(message)
                    return
                }
                const applicationId = props.applicationId
                const data = {
                    pageId: formId.value, // 表单id
                    applicationId, // 应用id
                    name: name.value, // 模板名称
                    columnList: targetKeys.value
                }
                props.addExportTemplate(data).then(() => {
                    initData()
                    getExportTemplateList()
                    createMessage.success('操作成功')
                })
            }
            const checkTableData = () => {
                if (!name.value) {
                    return { status: false, message: '请填写配置名字' }
                }
                if (!targetKeys.value.length) {
                    createMessage.error('请选择要导出的字段')
                    return { status: false, message: '请选择要导出的字段' }
                }
                return { status: true, message: '' }
            }
            onMounted(() => {
                initData()
                getExportTemplateList()
            })
            watch(
                () => targetKeys,
                () => {
                    selectLeft.value = []
                }
            )

            return {
                checkTableData,
                getRowSelection,
                selectLeft,
                name,
                handleSave,
                handlerDeleteConfirm,
                tableListColumns,
                dataSource,
                tableColumns,
                onChange,
                exportTemplateList,
                targetKeys
            }
        }
    })
</script>

<style lang="less" scoped>
    .templateManagePage {
        padding: 20px;
    }
    .templateManagePage
        :deep(.@{ant-prefix}-transfer-customize-list .@{ant-prefix}-transfer-list-body-customize-wrapper) {
        padding: 12px;
    }

    .templateManagePage .header {
        margin-bottom: 18px;
        display: flex;
        justify-content: flex-start;
    }
    .templateManagePage .header .@{ant-prefix}-input {
        width: 30%;
        margin-right: 20px;
    }

    .templateManagePage :deep(.@{ant-prefix}-transfer-list:first-child) {
        width: 33%;
        flex: none;
    }

    .templateManagePage :deep(.@{ant-prefix}-checkbox-group) {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
    }

    .templateManagePage :deep(.@{ant-prefix}-checkbox-wrapper + .@{ant-prefix}-checkbox-wrapper) {
        margin: 0;
    }

    .templateManagePage .title {
        border-left: 2px solid #3875ff;
        margin: 14px 0;
        text-indent: 5px;
    }

    .templateManagePage .template-list {
        margin-left: 20px;
    }

    .templateManagePage :deep(.@{ant-prefix}-transfer-customize-list .@{ant-prefix}-transfer-list) {
        height: calc(100vh - 120px);
        overflow: auto;
    }
</style>
